# -*-coding:utf-8 -*-

"""
# File       : AuthenByDecorator.py
# Time       ：2022/9/1 下午11:45
# Author     ：puppet
# version    ：python 3.8.1
# Description：
"""
import datetime
import time
from functools import wraps
from django.contrib.auth import authenticate, login
from rest_framework.authtoken.models import Token
from rent.utils.commonConfig import returnOriginJson,tokenTag
from django.http import JsonResponse, HttpResponse
import json, jwt
from rent.models import User, UserExtend
from django.contrib import auth
from rentalsite.settings import tokenExpireDays



# tokenTag = 'HTTP_AUTHORIZATION_TOKEN'


def loginRequeired(func):
    @wraps(func)
    def _decorator(request, *args, **kwargs):
        results = dict(returnOriginJson)
        if tokenTag in list(request.META.keys()):
            tokenAuth = bytes(str(request.META[tokenTag]), encoding='utf8')
            # input = json.loads(request.body).get('input')
            print("loginRequeired:", tokenAuth)
            try:
                decodedTokenAuth = jwt.decode(tokenAuth, 'secretKey', algorithm='HS256')
                # print('loginRequeired:', decodedTokenAuth, isinstance(decodedTokenAuth, dict))
                try:
                    # todo token里的username和接口入参里的username不一致的时候也能请求到数据，需要修复
                    username = dict(decodedTokenAuth).get('username', None)
                    password = dict(decodedTokenAuth).get('password', None)
                    tokentime = dict(decodedTokenAuth).get('tokentime', None)
                    if User.objects.filter(username=username).exists():
                        userObj = auth.authenticate(username=username, password=password)
                        if userObj:
                            userid = User.objects.filter(username=username).values('id')[0].get('id', 0)
                            tokenExpireTime = UserExtend.objects.filter(user=userid).values('tokenExpireTime')[
                                0].get(
                                'tokenExpireTime', 0)
                            timeNow = datetime.datetime.now()
                            if timeNow < tokenExpireTime and time.time() < tokentime +  tokenExpireDays * 24 * 60 * 60:
                                request.username = username
                                return func(request, *args, **kwargs)
                            else:
                                results['status'] = 401
                                results['isLogin'] = 'Token was expired.'
                                return JsonResponse(results)
                        else:
                            results['isLogin'] = 'Password is wrong.'
                            return JsonResponse(results)
                    else:
                        results['isLogin'] = 'There is no such user.'
                        return JsonResponse(results)
                except Exception as e:
                    print(e)
            except Exception as e:
                print(e)
                results['isLogin'] = 'Token is wrong.'
                return JsonResponse(results)
        else:
            results['isLogin'] = 'There is no token in header.'
            return JsonResponse(results)
    return _decorator
